package org.game.manager;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.cfg.DungeonLevelGroupCfg;
import org.cfg.cache.DungeonLevelGroupCfgCache;
import org.error.GameErrorCode;
import org.game.constant.DungeonConstant;
import org.game.db.bean.DungeonLevel;
import org.game.db.bean.DungeonLevelGroup;
import org.game.db.bean.Player;
import org.game.db.cache.DungeonLevelCache;
import org.game.db.cache.DungeonLevelGroupCache;
import org.game.log.builder.LogDsp;
import org.game.log.dsp.GoodsDsp;
import org.game.module.dungeonbo.DungeonBO;
import org.game.module.fight.handler.MainDungeonHandler;
import org.game.msgBuilder.DungeonMsgBuilder;
import org.game.protobuf.s2c.S2CItemMsg;
import org.game.util.ProtoUnit;

import com.google.common.collect.Maps;
import com.sojoys.artifact.tools.ToolError;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;

/**
 * 副本管理者
 * Created by fxf on 2017/11/22.
 */
public class DungeonManager {

    static Log log = LogFactory.get(DatingManager.class);


    /**
     * 购买战斗次数
     */
    public static byte[] buyFightCount(Player player, int levelGroupCid) {
        DungeonLevelGroupCfg cfg = DungeonLevelGroupCfgCache.me().getById(levelGroupCid);
        ToolError.isAndTrue(GameErrorCode.CLIENT_PARAM_IS_ERR, "没有找到配置", cfg == null);
        DungeonLevelGroup levelGroup = getOrInitDungeonLevelGroup(player, levelGroupCid);
        ToolError.isAndTrue(GameErrorCode.BUY_COUNT_IS_LIMIT, "购买次数已达上限", levelGroup.getBuyCount() >= cfg.getBuyCountLimit());

        LogDsp log = LogDsp.newBuilder(GoodsDsp.BUY_LEVEL_GROUP_FIGHT_COUNT).targetTag(levelGroupCid);
        
        ItemManager.costGoodsByCid(player, cfg.getPrice(), log, S2CItemMsg.ItemList.newBuilder());
        levelGroup.setBuyCount(levelGroup.getBuyCount() + 1);
        levelGroup.update();

        player.getPlayerProxy().sendMsg(DungeonBO.updateLevelGroupInfo,DungeonMsgBuilder.getUpdateLevelGroupInfo(levelGroup));
        return ProtoUnit.toByte(DungeonMsgBuilder.buildBuyFightCountMsg(levelGroupCid));
    }

    /**
     * 获取或新建副本组对象
     */
    public static DungeonLevelGroup getOrInitDungeonLevelGroup(Player player, int groupCid) {
        DungeonLevelGroup group = DungeonLevelGroupCache.me().getByPlayerIdCid(player.getId(), groupCid);
        if (group == null) {
            group = new DungeonLevelGroup(0L, 0, 0, new Date(), Maps.newHashMap(), player.getId(), groupCid, 0, 0);
            group.insert();
            player.getPlayerProxy().sendMsg(DungeonBO.updateLevelGroupInfo,DungeonMsgBuilder.getUpdateLevelGroupInfo(group));
        }
        return group;
    }

    public static void refreshDungeonCount(Player player){
        List<DungeonLevelGroup> groupList = DungeonLevelGroupCache.me().getByPlayerId(player.getId());
        long now = System.currentTimeMillis();
        groupList.forEach(group -> {
            DungeonLevelGroupCfg cfg = group.getDungeonLevelGroupProxy().getCfg();
            if (cfg != null && cfg.getCycleType() == DungeonConstant.FIGHT_COUNT_REFRESH_TYPE_DAILY) {
                group.getDungeonLevelGroupProxy().refreshCount(now);
            }
        });

        List<DungeonLevel> levelList = DungeonLevelCache.me().getByPlayerId(player.getId());
        levelList.forEach(level->{
            level.getDungeonLevelProxy().refreshFightCount(now);
        });

    }


    /**
     * 领取副本组奖励
     */
    public static byte[] getLevelGroupReward(Player player, int levelGroupCid, int difficulty, int starNum) {
        DungeonLevelGroup levelGroup = getOrInitDungeonLevelGroup(player, levelGroupCid);
        ToolError.isAndTrue(GameErrorCode.LEVEL_GROUP_REWARD_IS_GETTED, "奖励已经领取", levelGroup.getDungeonLevelGroupProxy().isGettedReward(difficulty, starNum));
        ToolError.isAndTrue(GameErrorCode.STAR_NUM_IS_NOT_ENOUGH, "星数不足", getLevelGroupStarNum(player, levelGroupCid, difficulty) < starNum);
        Map<Integer, Integer> reward = levelGroup.getDungeonLevelGroupProxy().getCfg().getRewardByDifficultyAndStar(difficulty, starNum);
        ToolError.isAndTrue(GameErrorCode.CLIENT_PARAM_IS_ERR, "参数传递错误,没有这个星数奖励", reward == null || reward.size() == 0);
        //ToolError.isAndTrue(GameErrorCode.BAG_SPACE_IS_NOT_ENOUGH, "背包空间不足", !ItemManager.checkBackpackSpace(player, reward));

        levelGroup.getDungeonLevelGroupProxy().recordReward(difficulty, starNum);
        
        LogDsp log = LogDsp.newBuilder(GoodsDsp.LEVEL_GROUP_REWARD).addAttr("levelGroupCid", levelGroupCid).addAttr("difficulty", difficulty).addAttr("starNum", starNum);
        ItemManager.addGoodsAndPush(player, null, null, reward, log);

        return ProtoUnit.toByte(DungeonMsgBuilder.getLevelGroupReward(levelGroupCid, difficulty, starNum,levelGroup));
    }

    /**
     * 获取副本组的星数
     */
    private static int getLevelGroupStarNum(Player player, int groupCid, int difficulty) {

        List<DungeonLevel> list = player.getDungeonLevelsFkPlayerId();
        return list.stream()
                .filter(level -> level.getDungeonLevelProxy().getCfg().getLevelGroupId() == groupCid)//通过groupCid筛选
                .filter(level -> level.getDungeonLevelProxy().getCfg().getDifficulty() == difficulty)//通过难度筛选
                .mapToInt(level -> level.getAchieveGoals().size())
                .sum();//统计星数
    }

    
	public static byte[] promoteStory(Player player, int dungeonTypeMainLine, int cid) {
		return MainDungeonHandler.promoteStory(player, dungeonTypeMainLine, cid);
	}

}
